package com.hxzy.service.impl;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hxzy.common.enums.AckCode;
import com.hxzy.common.exception.ServiceException;
import com.hxzy.common.util.WaimaiThreadLocal;
import com.hxzy.controller.admin.login.resp.AdminLoginResp;
import com.hxzy.controller.admin.mapstruct.ProductConvert;
import com.hxzy.controller.admin.product.dto.DishFlavorItem;
import com.hxzy.controller.admin.product.dto.DishFlavorProperty;
import com.hxzy.controller.admin.product.req.ProductAddReq;
import com.hxzy.controller.admin.product.req.ProductEditReq;
import com.hxzy.controller.admin.product.req.ProductReq;
import com.hxzy.controller.admin.product.resp.ProductResp;
import com.hxzy.controller.mobile.product.req.MobileProductReq;
import com.hxzy.controller.mobile.product.resp.MobileProductResp;
import com.hxzy.entity.DishFlavor;
import com.hxzy.entity.Product;
import com.hxzy.mapper.DishFlavorMapper;
import com.hxzy.service.ProductService;
import com.hxzy.mapper.ProductMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.Executors;

/**
* @author Administrator
* @description 针对表【product(商品信息)】的数据库操作Service实现
* @createDate 2023-06-28 16:38:45
*/

@Service
public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product>
    implements ProductService{

    @Autowired
    private ProductMapper productMapper;

    /**
     * 商品口味
     */
    @Autowired
    private DishFlavorMapper dishFlavorMapper;


    @Override
    public PageInfo<ProductResp> search(ProductReq req) {

        return PageHelper.startPage(req.getPage(),req.getSize())
                .doSelectPageInfo(()->{
                    List<ProductResp> arr=productMapper.search(req);
                    //需要再一次组装的
                    for(ProductResp p: arr){

                        LambdaQueryWrapper<DishFlavor> queryWrapper=new LambdaQueryWrapper<>();
                        queryWrapper.eq(DishFlavor::getDishId, p.getId());
                        queryWrapper.eq(DishFlavor::getIsDeleted,"0");
                        List<DishFlavor> dishFlavorList = dishFlavorMapper.selectList(queryWrapper);

                        //组装成自己定义的口味数据给前端
                        List<DishFlavorProperty> propertyList=new ArrayList<>();

                        dishFlavorList.stream().forEach(s-> {
                            DishFlavorProperty property=new DishFlavorProperty();
                            property.setName( s.getName());
                            //json反序列化
                            List<DishFlavorItem> dishFlavorItems = JSONUtil.toList(s.getValue(), DishFlavorItem.class);
                            property.setValue(dishFlavorItems);
                            propertyList.add(property );
                        });
                        p.setDishFlavors(propertyList);
                    }


              });
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean add(ProductAddReq req) {
        AdminLoginResp adminLoginResp= WaimaiThreadLocal.getCurrent();
        //创建要保存的产品
        Product entity = ProductConvert.INSTANCE.convert(req);
        entity.setMerchantId(adminLoginResp.getId());
        entity.setScore(5);

        boolean save = this.save(entity);
        //保存成功，判断是否有口味
        if(save){
            List<DishFlavorProperty> dishFlavors = req.getDishFlavors();
            if(dishFlavors!=null && dishFlavors.size()>0){
                for(DishFlavorProperty  p: dishFlavors) {
                    DishFlavor dishFlavor = new DishFlavor();
                    dishFlavor.setName(p.getName());
                    //json序列化
                    dishFlavor.setValue(JSONUtil.toJsonStr(p.getValue()));
                    dishFlavor.setDishId(entity.getId());
                    dishFlavor.setIsDeleted("0");
                    this.dishFlavorMapper.insert(dishFlavor);
                }
            }
        }
        return save;
    }

    @Override
    public ProductResp findById(Long id) {
        AdminLoginResp adminLoginResp = WaimaiThreadLocal.loginVOThreadLocal.get();

        LambdaQueryWrapper<Product> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(Product::getId,id);
        wrapper.eq(Product::getMerchantId,adminLoginResp.getId());

        Product db = this.getOne(wrapper);

        if (Objects.isNull(db)) {
            throw new ServiceException(AckCode.NOT_FOUND_DATA);
        }

        ProductResp resp = ProductConvert.INSTANCE.convert(db);

        //查询口味信息
        LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DishFlavor::getDishId, db.getId());
        queryWrapper.eq(DishFlavor::getIsDeleted, "0");
        List<DishFlavor> dishFlavorList = dishFlavorMapper.selectList(queryWrapper);

        //组装成自己定义的口味数据给前端
        List<DishFlavorProperty> propertyList = new ArrayList<>();

        dishFlavorList.stream().forEach(s -> {
            DishFlavorProperty property = new DishFlavorProperty();
            property.setName(s.getName());
            //json反序列化
            List<DishFlavorItem> dishFlavorItems = JSONUtil.toList(s.getValue(), DishFlavorItem.class);
            property.setValue(dishFlavorItems);
            propertyList.add(property);
        });

        resp.setDishFlavors(propertyList);

        return resp;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean edit(ProductEditReq req) {
        Product db = this.getById(req.getId());
        if (Objects.isNull(db)) {
            throw new ServiceException(AckCode.NOT_FOUND_DATA);
        }

        //不允许修改其它商家的数据
        if(!req.getMerchantId().equals(WaimaiThreadLocal.getCurrent().getId())){
            throw new ServiceException(AckCode.VALUE_NOT_CHANGE);
        }

        Product entity = ProductConvert.INSTANCE.convert(req);
        boolean save = this.updateById(entity);
        if(save){
            //先删除原有的口味数据
            LambdaQueryWrapper<DishFlavor> deleteQueryWrapper=new LambdaQueryWrapper<>();
            deleteQueryWrapper.eq(DishFlavor::getDishId, entity.getId());
            this.dishFlavorMapper.delete(deleteQueryWrapper);

            //再判断本次是否要添加口味
            if(req.getDishFlavors()!=null && req.getDishFlavors().size()>0){
                for(DishFlavorProperty  p: req.getDishFlavors()) {
                    DishFlavor dishFlavor = new DishFlavor();
                    dishFlavor.setName(p.getName());
                    //json序列化
                    dishFlavor.setValue(JSONUtil.toJsonStr(p.getValue()));
                    dishFlavor.setDishId(entity.getId());
                    dishFlavor.setIsDeleted("0");
                    this.dishFlavorMapper.insert(dishFlavor);
                }
            }
        }
        return save;
    }

    /**
     * 商品上下线
     * @param ids
     * @param status
     * @return
     */
    @Override
    public boolean upOrDown(Long[] ids, String status) {
        LambdaQueryWrapper<Product> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.in(Product::getId,ids);

        Product product=new Product();
        product.setIsgrounding(status);

        boolean save = this.update(product, queryWrapper);
        return save;
    }

    /**
     * 手机端查询
     * @param req
     * @return
     */
    @Override
    public List<MobileProductResp> mobileSearch(MobileProductReq req) {
        List<MobileProductResp> mobileProductResps = this.productMapper.mobileSearch(req);
        //查询口味明细
        mobileProductResps.stream().forEach(p-> {

            //查询口味信息
            LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(DishFlavor::getDishId, p.getId());
            queryWrapper.eq(DishFlavor::getIsDeleted, "0");
            List<DishFlavor> dishFlavorList = dishFlavorMapper.selectList(queryWrapper);

            //组装成自己定义的口味数据给前端
            List<DishFlavorProperty> propertyList = new ArrayList<>();


            dishFlavorList.stream().forEach(s -> {
                DishFlavorProperty property = new DishFlavorProperty();
                property.setName(s.getName());
                //json反序列化
                List<DishFlavorItem> dishFlavorItems = JSONUtil.toList(s.getValue(), DishFlavorItem.class);
                property.setValue(dishFlavorItems);
                propertyList.add(property);
            });

            //添加到商品
            p.setDishFlavors(propertyList);

        });

        return mobileProductResps;
    }

    /**
     * 查询商品中并加锁
     * @param dishId
     * @return
     */
    @Override
    public ProductResp lockById(Long dishId) {
        Product product = super.baseMapper.pessimisticLockById(dishId);
        return ProductConvert.INSTANCE.convert(product);
    }

    /**
     * 减库存
     * @param id 商品ID
     * @param num 数量
     * @return
     */
    @Override
    public int descNum(Long id, int num) {
        return super.baseMapper.descNum(id,num);
    }
}




